<?php

//    Socket PHP Class.
//	  Turning Sockets OO, and making them a lot more enjoyable to work with..

//    Copyright (C) 2009 Kirth 'Sebastian'.
//
//    This code is property of the CodeArray PHP project.  Rights Reserved!
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

define('SOCK_COULD_NOT_CONNECT', 10);
define('SOCK_COULD_NOT_WRITE',   11);
define('SOCK_COULD_NOT_READ',    12);

class Socket
{
	
	private $socket;
	private $error;
	
	private $arguments;
	
	private $timeout;
	
	public function __construct($host, $port, $timeout = 10) {
		$this->socket = @fsockopen($host, $port, $eNum, $eStr, $timeout);
		
		if(!$this->socket) {
			throw new Exception('Could not connect to {' . $host . '}:{' . $port . '}
								 failed. ' . $eStr, SOCK_COULD_NOT_CONNECT);
		}
	}
	
	public function _destruct() {
		$this->Disconnect();
	}
	
	public function Disconnect() {
		if(!@fclose($this->socket))
			throw new Exception('Could not close connection. ' . $eStr, SOCK_COULD_NOT_CLOSE);
	}
	
	public function WriteLine($w) {
		if(!$this->socket)
			throw new Exception('Could not write. ' . $eStr, SOCK_COULD_NOT_WRITE);
		
		if(!@fwrite($this->socket, $w . "\r\n"))
			throw new Exception('Could not write. ' . $eStr, SOCK_COULD_NOT_WRITE);
	}
	
	public function Write($w) {
		if(!$this->socket)
			throw new Exception('Could not write. ' . $eStr, SOCK_COULD_NOT_WRITE);
		
		if(!@fwrite($this->socket, $w))
			throw new Exception('Could not write. ' . $eStr, SOCK_COULD_NOT_WRITE);
	}
	
	public function Read() {
		if(!$this->socket)
			throw new Exception('Could not read. ' . $eStr, SOCK_COULD_NOT_READ);
					
		return @fgets($this->socket, 128);
	}
	
	
	public function valConnection() {
		return(is_resource($this->socket && (!$this->socket)));
	}
	
	
	
	

}

?>

<?php
/*
set_time_limit(20);

try {
 $sock = new Socket("irc.wyldryde.org", 6667);
 $sock->WriteLine("HELIUM!");
 while(1) {
	while($d = $sock->Read()) {
		echo nl2br($d);
		flush();
	}
 }
} catch(Exception $e) {
	echo $e->getCode() . ' : ' . $e->getMessage();
}
*/
?>